<template>
  <el-card>
    <el-form ref="addForm" :model="addData" :rules="rules" label-width="100px">
      <el-form-item prop="rolename" label="角色名称">
        <el-input
          v-model="addData.rolename"
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="menus" label="角色权限">
        <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="defaultProps"
          ref="tree"
        >
        </el-tree>
      </el-form-item>
      <el-form-item prop="status" label="状态">
        <el-radio-group v-model="addData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即提交</el-button>
        <el-button type="default" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {getMenuList} from '../../request/menu'
export default {
    data(){
        const menuValidate=(rule,value,callback)=>{
            const checkedKeys=this.$refs.tree.getCheckedKeys()
            if(checkedKeys.length==0){
                callback(new Error('请选择操作权限'))
            }
            callback()
        
        }
        return{
            addData:{
                rolename:'',
                menus:'',
                status:1

            }
            ,rules:{
                rolename:{required:true,message:"请输入角色名称"},
                menus:{validator:menuValidate,tigger:'blur'},
                status:{required:true,message:'请选择状态'}
            },
            data:[],
            defaultProps:{
                children:'children',
                label:'title'
            }
        }
    },
    created(){
        this.getMenuList()
    },
    methods:{
        submitForm(){
            this.$refs.addForm.validate(async valid=>{
                if(valid){
                    this.addData.menus=this.$refs.tree.getCheckedKeys().join(',')
                    const res=await this.$http.post('/api.roleadd',this.addData)
                    if(res.code==200){
                        this.$success(res.msg)
                        return this.$router.push('/role')
                    }
                    this.$error(res.msg)
                }
            })
        },
        resetForm(){
            this.$refs.addForm.resetFields()
        },
        async getMenuList(){
            const list=await getMenuList()
            if(list){
                this.data=list
            }
        }
    }
};
</script>

<style lang='less' scoped>
.el-form{
    width: 600px;
    margin: 0 auto;
}
</style>